package com.otree.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.google.gson.GsonBuilder;
import com.otree.constant.RedisConstant;
import com.otree.entity.Message;
import com.otree.entity.SysUserEntity;
import com.otree.service.SysUserService;
import com.otree.utils.MyWebSocketHandler;
import com.otree.utils.R;
import com.otree.utils.RedisCacheConfig;
import com.otree.utils.ShiroUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.socket.TextMessage;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录相关
 * 
 * @author forest
 */
@Controller
public class SysLoginController {
	@Autowired
	private Producer producer;
	@Resource
	protected RedisCacheConfig redisCacheConfig;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private  MyWebSocketHandler handler;
	@Autowired
	private HttpServletRequest request;


	
	@RequestMapping("captcha.jpg")
	public void captcha(HttpServletResponse response)throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
	}
	
	/**
	 * 登录
	 */
	@ResponseBody
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
	public R login(String username, String password, String captcha)throws IOException {
		String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
		if(!captcha.equalsIgnoreCase(kaptcha)){
			return R.error("验证码不正确");
		}
		try{
			 //查询用户信息
	        SysUserEntity user = sysUserService.queryByUserName(username);
            redisCacheConfig.hset(RedisConstant.USER, username, user.getPassword()+"|"+user.getStatus()+"|"+user.getUserId());
			Subject subject = ShiroUtils.getSubject();
			//sha256加密
			password = new Sha256Hash(password).toHex();
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			//使用shiro来验证
			token.setRememberMe(true);
			request.getSession().setAttribute("user",user);
			subject.login(token);
		}catch (UnknownAccountException e) {
			return R.error(e.getMessage());
		}catch (IncorrectCredentialsException e) {
			return R.error(e.getMessage());
		}catch (LockedAccountException e) {
			return R.error(e.getMessage());
		}catch (AuthenticationException e) {
			return R.error("账户验证失败");
		}
	    
		return R.ok();
	}
	@ResponseBody
	@RequestMapping(value = "/msg/talkLogin", method = RequestMethod.POST)
	public ModelAndView doLogin(Long userId, HttpServletRequest request) {

		Map<Long, SysUserEntity> userse = new HashMap<>();
		SysUserEntity user = sysUserService.queryObject(userId);
		userse.put(user.getUserId(),user);

		request.getSession().setAttribute("uid", user.getUserId());
		request.getSession().setAttribute("name", userse.get(user.getUserId()).getUsername());
		return new ModelAndView("talk");
	}
	// 跳转到发布广播页面
	@RequestMapping(value = "/msg/broadcast", method = RequestMethod.GET)
	public ModelAndView broadcast() {
		return new ModelAndView("broadcast");
	}

	// 发布系统广播（群发）
	@ResponseBody
	@RequestMapping(value = "/msg/broadcast", method = RequestMethod.POST)
	public void broadcast(String text) throws IOException {
		Message msg = new Message();
		msg.setDate(new Date());
		msg.setFrom(-1L);
		msg.setFromName("系统广播");
		msg.setTo(0L);
		msg.setText(text);
		handler.broadcast(new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg)));
	}
	/**
	 * 退出
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:login.html";
	}
	
}
